package com.tbl.modules.wms.service.Impl.pad;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.dao.system.UserDAO;
import com.tbl.modules.platform.entity.system.User;
import com.tbl.modules.wms.constant.PdaResult;
import com.tbl.modules.wms.dao.allo.AlloInStorageDAO;
import com.tbl.modules.wms.dao.allo.AlloOutStorageDAO;
import com.tbl.modules.wms.dao.allo.AllocationDAO;
import com.tbl.modules.wms.dao.allo.AllocationDetailDAO;
import com.tbl.modules.wms.dao.baseinfo.CarDAO;
import com.tbl.modules.wms.dao.baseinfo.DishDAO;
import com.tbl.modules.wms.dao.baseinfo.FactoryAreaDAO;
import com.tbl.modules.wms.dao.baseinfo.ShelfDAO;
import com.tbl.modules.wms.dao.instorage.InstorageDAO;
import com.tbl.modules.wms.dao.instorage.InstorageDetailDAO;
import com.tbl.modules.wms.dao.move.MoveInStorageDAO;
import com.tbl.modules.wms.dao.move.MoveOutStorageDAO;
import com.tbl.modules.wms.dao.move.MoveStorageDetailDAO;
import com.tbl.modules.wms.dao.outstorage.OutStorageDetailDAO;
import com.tbl.modules.wms.dao.outstorage.OutstorageDAO;
import com.tbl.modules.wms.dao.pad.PadDAO;
import com.tbl.modules.wms.dao.pda.PdaDAO;
import com.tbl.modules.wms.dao.pda.RfidBindDAO;
import com.tbl.modules.wms.dao.pda.SplitInstorageDAO;
import com.tbl.modules.wms.dao.storageinfo.StorageInfoDAO;
import com.tbl.modules.wms.entity.allo.AlloInStorage;
import com.tbl.modules.wms.entity.allo.AlloOutStorage;
import com.tbl.modules.wms.entity.allo.Allocation;
import com.tbl.modules.wms.entity.allo.AllocationDetail;
import com.tbl.modules.wms.entity.baseinfo.Car;
import com.tbl.modules.wms.entity.baseinfo.Dish;
import com.tbl.modules.wms.entity.baseinfo.FactoryArea;
import com.tbl.modules.wms.entity.baseinfo.Shelf;
import com.tbl.modules.wms.entity.instorage.Instorage;
import com.tbl.modules.wms.entity.instorage.InstorageDetail;
import com.tbl.modules.wms.entity.move.MoveInStorage;
import com.tbl.modules.wms.entity.move.MoveOutStorage;
import com.tbl.modules.wms.entity.move.MoveStorageDetail;
import com.tbl.modules.wms.entity.outstorage.OutStorage;
import com.tbl.modules.wms.entity.outstorage.OutStorageDetail;
import com.tbl.modules.wms.entity.split.RfidBind;
import com.tbl.modules.wms.entity.split.SplitInstorage;
import com.tbl.modules.wms.entity.storageinfo.StorageInfo;
import com.tbl.modules.wms.service.interfacelog.InterfaceDoService;
import com.tbl.modules.wms.service.pad.PadService;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static java.lang.Long.parseLong;
import static java.lang.Long.valueOf;

/**
 * Pad接口实现
 * @author 70486
 */
@Service
public class PadServiceImpl extends ServiceImpl<PadDAO, T> implements PadService {

    /**
     * 手持机
     */
    @Autowired
    private PdaDAO pdaDAO;
    /**
     * 库存
     */
    @Autowired
    private StorageInfoDAO storageInfoDAO;
    /**
     * 调拨管理
     */
    @Autowired
    private AllocationDAO allocationDAO;
    /**
     * 调拨管理-调拨详情
     */
    @Autowired
    private AllocationDetailDAO allocationDetailDAO;
    /**
     * 调拨入库管理
     */
    @Autowired
    private AlloInStorageDAO alloInStorageDAO;
    /**
     * 调拨出库
     */
    @Autowired
    private AlloOutStorageDAO alloOutStorageDAO;
    /**
     * 移库处理详情
     */
    @Autowired
    private MoveStorageDetailDAO moveStorageDetailDAO;
    /**
     * 移库入库
     */
    @Autowired
    private MoveInStorageDAO moveInStorageDAO;
    /**
     * 移库出库
     */
    @Autowired
    private MoveOutStorageDAO moveOutStorageDAO;
    /**
     * 入库管理-订单详情
     */
    @Autowired
    private InstorageDetailDAO instorageDetailDAO;
    /**
     * 入库管理-订单
     */
    @Autowired
    private InstorageDAO instorageDAO;
    /**
     * 出库详情
     */
    @Autowired
    private OutStorageDetailDAO outStorageDetailDAO;
    /**
     * 用户管理
     */
    @Autowired
    private UserDAO userDAO;
    /**
     * 拆分入库
     */
    @Autowired
    private SplitInstorageDAO splitInstorageDAO;
    /**
     * rfid绑定
     */
    @Autowired
    private RfidBindDAO rfidBindDAO;
    /**
     * 厂区
     */
    @Autowired
    private FactoryAreaDAO factoryAreaDAO;
    /**
     * 盘具信息
     */
    @Autowired
    private DishDAO dishDAO;
    /**
     * 行车信息
     */
    @Autowired
    private CarDAO carDAO;
    /**
     * 库位管理
     */
    @Autowired
    private ShelfDAO shelfDAO;
    /**
     * 出库信息
     */
    @Autowired
    private OutstorageDAO outstorageDAO;
    /**
     * 接口执行
     */
    @Autowired
    private InterfaceDoService interfaceDoService;

    /**
     * 功能描述:用户登陆
     * @param username 登陆用户
     * @param password 登陆密码
     * @return PdaResult 菜单列表等
     */
    @Override
    public PdaResult login(String username, String password) {
        List<User> users = userDAO.selectByMap(new HashMap<String, Object>() {{
            put("USERNAME", username);
            put("PASSWORD", new SimpleHash("SHA-1", password, username).toString()); // 密码加密
        }});
        if (users == null || users.size() != 1){
            return new PdaResult(1, "用户名密码输入错误", "");
        }

        return new PdaResult(new HashMap<String, Object>() {{
            put("userId", users.get(0).getUserId());
            put("value","0");
            put("menuList", pdaDAO.getMenuList(users.get(0).getRoleId(), 3));
        }});
    }

    /**
     * 模块：入库管理
     * 接口编号：1.1
     * 功能描述: 获取详情列表
     * 入参：userId;carCode
     * 返回：详情表列表 状态为已开始,未完成的
     */
    @Override
    public PdaResult storageInList(Long userId,String carCode) {
        User user = userDAO.selectById(userId);
        if (user == null || user.getFactoryCode() == null){
            return new PdaResult(1, "用户异常", "");
        }
        return new PdaResult(instorageDetailDAO.selectList(new EntityWrapper<InstorageDetail>()
                .eq("CARCODE", carCode)
                .eq("STATE", 3)
                .in("ORG", user.getFactoryCode())));
    }

    /**
     * 模块：入库管理
     * 接口编号：1.2
     * 功能描述: 入库完成
     * 入参：rfid,shelfCode(库位编码),userId(用户主键),date(事务处理日期)
     * 返回：PdaResult
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PdaResult storageInSuccess(String rfid, String shelfCode, Long userId, String date) {
        List<InstorageDetail> lstInstorageDetail = instorageDetailDAO.selectByMap(new HashMap<String, Object>(1) {{
            put("RFID", rfid);
        }});
        if (lstInstorageDetail == null || lstInstorageDetail.size() != 1){
            return new PdaResult(1, "数据异常", "");
        }

        InstorageDetail instorageDetail = lstInstorageDetail.get(0);
        Instorage instorage = instorageDAO.selectById(instorageDetail.getPId());
        if (instorage == null){
            return new PdaResult(1, "数据异常", "");
        }

        List<StorageInfo> lstStorageInfo = storageInfoDAO.selectList(new EntityWrapper<StorageInfo>().eq("QACODE", instorageDetail.getQaCode()));
        //如果存在了，则不能重复新增
        if(lstStorageInfo.size()>0) {
            return new PdaResult(1,"已存在，不能重复入库","");
        }

        List<FactoryArea> factorySerialnumList = factoryAreaDAO.selectByMap(new HashMap<String,Object>(){{
            put("CODE",instorageDetail.getFactoryCode());
        }});
        //流水号
        String serialnum = factorySerialnumList.size()>0?factorySerialnumList.get(0).getSerialnum():"";
        if(StringUtils.isNotEmpty(serialnum)) {
            serialnum = String.format("%04d", Integer.parseInt(serialnum)+1);
        }else {
            serialnum = "0001";
        }
        if(factorySerialnumList.size()>0) {
            FactoryArea fa = factorySerialnumList.get(0);
            fa.setSerialnum(serialnum);
            factoryAreaDAO.updateById(fa);
        }
        Dish dish = dishDAO.selectOne(new Dish() {{
            setCode(instorageDetail.getDishnumber());
        }});
        //成品电缆盘号
        String drumno = shelfCode.charAt(0) + ("铁木盘".equals(dish.getDrumType()) ? "1" : "全木盘".equals(dish.getDrumType()) ? "2" : "3")
    			+ parseLong(dish.getOuterDiameter())/10 + DateUtils.getDays().substring(2) + serialnum;

        //调MES入库接口
        if(instorageDetail.getStoragetype()==0) {
        	Map<String,Object> xmlMap = new HashMap<>(2);
        	xmlMap.put("orgid", instorageDetail.getFactoryCode());
        	xmlMap.put("batches", new HashMap<String,Object>(1){{
        		put("batch",new HashMap<String,Object>(3){{
        			put("batchno",instorageDetail.getBatchNo());
        			put("invlocation",instorageDetail.getShelfCode());
                    //成品电缆盘号
        			put("drumno",drumno);
        		}});
        	}});
        	
        	interfaceDoService.insertDo("FEMES001", "MES入库接口（正常入库）", JSONObject.toJSONString(xmlMap), DateUtils.getTime(),
                    instorageDetail.getQaCode(),instorageDetail.getBatchNo(), null, "");
        }else if(instorageDetail.getStoragetype()==1) {
            //销售退货入库
			Map<String,Object> params = new HashMap<>(1);
			params.put("line", new HashMap<String,Object>(4){{
                //组织id
				put("orgid",instorageDetail.getFactoryCode());
                //物料编码
				put("itemnumber",instorageDetail.getMaterialCode());
                //客户id
				put("customerid",instorageDetail.getCustomerid());
                //员工编号
				put("employeenum",userDAO.selectById(userId).getUsername());
                put("quantity",instorageDetail.getMeter());
                //事务处理日期
				put("transdate",date);
                //地址id
				put("locatornum",instorageDetail.getShelfCode());
                //销售订单头id
				put("oeheaderid",instorageDetail.getOeheader());
                //销售订单行id
				put("oelineid",instorageDetail.getOeline());
                //批次号
				put("lotnumber",instorageDetail.getBatchNo());
			}});

			interfaceDoService.insertDo("FEWMS024", "EBS接口-销售退货入库", JSONObject.toJSONString(params), DateUtils.getTime(),instorageDetail.getQaCode(),
                    instorageDetail.getBatchNo(), null, "");
        }else if(instorageDetail.getStoragetype()==2) {
            //外采入库
	    	Map<String,Object> params = new HashMap<>(1);
	    	params.put("line",new HashMap<String,Object>(10) {{
                //入库厂区编码
	    		put("orgid",instorageDetail.getOrg());
                //质保号
	    		put("qacode",instorageDetail.getQaCode());
                //报验单号
	    		put("inspectno",instorageDetail.getInspectno());
                //入库仓库
	    		put("worehouse",instorageDetail.getWarehouseCode());
                //库位
	    		put("location",instorageDetail.getShelfCode());
                //盘号
	    		put("panno",drumno);
                //批次号
	    		put("batchname",instorageDetail.getBatchNo());
                //事务处理日期
	    		put("trans_date",date);
	    	}});
	    	
	    	interfaceDoService.insertDo("FEWMS025", "EBS接口-外采入库", JSONObject.toJSONString(params), DateUtils.getTime(),instorageDetail.getQaCode(),
                    instorageDetail.getBatchNo(), null, "");
        }

        instorageDetail.setDishcode(drumno);
        instorageDetail.setShelfCode(shelfCode);
        instorageDetail.setInStorageId(userId);
        instorageDetail.setInstorageTime(new Date());
        instorageDetail.setState(4);
        instorageDetailDAO.updateById(instorageDetail);

        StorageInfo storageInfo = new StorageInfo();
        storageInfo.setMaterialCode(instorageDetail.getMaterialCode());
        storageInfo.setBatchNo(instorageDetail.getBatchNo());
        storageInfo.setQaCode(instorageDetail.getQaCode());
        storageInfo.setShelfCode(instorageDetail.getShelfCode());
        storageInfo.setWarehouseCode(instorageDetail.getWarehouseCode());
        storageInfo.setMeter(instorageDetail.getMeter());
        storageInfo.setRfid(instorageDetail.getRfid());
        storageInfo.setInStorageTime(new Date());
        storageInfo.setOrg(instorageDetail.getFactoryCode());
        storageInfo.setSalesCode(instorageDetail.getSalesCode());
        storageInfo.setSalesName(instorageDetail.getSalesName());
        storageInfo.setInStorageId(userId);
        storageInfo.setEntityNo(instorage.getEntityNo());
        //订单行号
        storageInfo.setOrderline(instorageDetail.getOrderline());
        //订单号
        storageInfo.setOrderno(instorageDetail.getOrdernum());
        storageInfo.setDishnumber(instorageDetail.getDishnumber());
        storageInfoDAO.insert(storageInfo);

        //恢复行车状态为可用
        Car car = carDAO.selectOne(new Car() {{
            setCode(instorageDetail.getCarCode());
        }});
        if(car!=null) {
            car.setState(2L);
            carDAO.updateById(car);
        }

        //库位不可用
        Shelf shelf = shelfDAO.selectOne(new Shelf() {{
            setCode(shelfCode);
            setWarehouseCode(instorageDetail.getWarehouseCode());
            setFactoryCode(instorageDetail.getFactoryCode());
        }});
        if(shelf!=null) {
            shelf.setState(0);
            shelfDAO.updateById(shelf);
        }
        return new PdaResult();
    }
    
    /**
     * 模块：入库管理
     * 接口编号：1.4
     * 功能描述: 入库:选择可用行车
     * 入参：warehouseCode(仓库编码);factoryCode(厂区编码)
     * 返回：行车列表
     */
    @Override
    public PdaResult storageinStorageinCar(String warehouseCode,String factoryCode) {
        return new PdaResult(carDAO.selectList(new EntityWrapper<Car>().eq("WAREHOUSECODE", warehouseCode).eq("FACTORYCODE", factoryCode)));
    }
    
    /**
     * 模块：出库管理
     * 接口编号：2.1
     * 功能描述: 获取详情列表
     * 入参：userId,carCode
     * 返回：详情表列表 状态为已开始,未完成的
     */
    @Override
    public PdaResult storageOutList(Long userId,String carCode) {
        User user = userDAO.selectById(userId);
        if (user == null || user.getFactoryCode() == null){
            return new PdaResult(1, "用户异常", "");
        }
        return new PdaResult(outStorageDetailDAO.selectByFactoryCode(Arrays.asList(user.getFactoryCode().split(",")),carCode));
    }

    /**
     * 模块：出库管理
     * 接口编号：2.2
     * 功能描述: 出库完成
     * 入参：rfid,meter(米数),userId(用户id)
     * 返回：PdaResult
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PdaResult storageOutSuccess(String rfid, String meter, Long userId) {
        List<OutStorageDetail> lstOutStorageDetail = outStorageDetailDAO.selectByMap(new HashMap<String, Object>() {{
            put("RFID", rfid);
        }});
        if (lstOutStorageDetail == null || lstOutStorageDetail.size() != 1) {
            return new PdaResult(1, "数据异常", "");
        }
        OutStorageDetail outStorageDetail = lstOutStorageDetail.get(0);
        //出库明细表中的米数
        String oriMeter = outStorageDetail.getMeter();
        //剩余米数
        String leftMeter = String.valueOf(Float.parseFloat(oriMeter) - Float.parseFloat(meter));
        //新的米数
        outStorageDetail.setMeter(meter);
        outStorageDetail.setOutStorageTime(new Date());
        outStorageDetail.setOutStorageId(userId);
        outStorageDetail.setState(3);
        //更新出库明细表
        outStorageDetailDAO.updateById(outStorageDetail);

        StorageInfo storageInfo ;
        List<StorageInfo> lstStorageInfo = storageInfoDAO.selectList(new EntityWrapper<StorageInfo>().eq("RFID",rfid));
        if(lstStorageInfo==null||lstStorageInfo.size() == 0){
            return new PdaResult(1, "库存中查无此数据", "");
        }else {
            storageInfo = lstStorageInfo.get(0);
        }

        //剩余米数为0
        if("0".equals(leftMeter)||"0.0".equals(leftMeter)) {
        	//库位可用
            Shelf shelf = shelfDAO.selectOne(new Shelf() {{
            	setCode(storageInfo.getShelfCode());
            	setWarehouseCode(storageInfo.getWarehouseCode());
            	setFactoryCode(storageInfo.getOrg());
            }});
            if(shelf!=null) {
            	shelf.setState(1);
            	shelfDAO.updateById(shelf);
            }
            OutStorage outStorage = outstorageDAO.selectById(outStorageDetail.getPId());
            //调正常出库接口
            Map<String,Object> xmlMap = new HashMap<>();
            xmlMap.put("line", new HashMap<String, Object>() {{
                put("outno", outStorage.getShipNo());
                put("userno", userDAO.selectById(userId).getUsername());
                put("batchs",new HashMap<String,Object>(){{
                	put("batchno",outStorageDetail.getBatchNo());
                }});
            }});
//            wmsService.FEWMS002(xmlMap);
            interfaceDoService.insertDo("FEMES001", "MES入库接口", JSONObject.toJSONString(xmlMap), DateUtils.getTime(),outStorageDetail.getQaCode(),
                    outStorageDetail.getBatchNo(), null, "");
            
            Car car = carDAO.selectOne(new Car() {{
            	setCode(outStorageDetail.getCarCode());
            }});
            if(car!=null) {
            	car.setState(2L);
            	carDAO.updateById(car);
            }
            return new PdaResult(storageInfoDAO.deleteById(storageInfo.getId())>0);
        }else{
            //批次号，rfid编码
            String batchNoAndrfid = pdaDAO.getseqsplitinstorage();
            String qaCode = storageInfo.getQaCode();
            String qaCodeBuff;
            List<RfidBind> lstRfidBind = rfidBindDAO.selectList(new EntityWrapper<RfidBind>().eq("OLDQACODE",qaCode).orderBy("ID"));
            if(lstRfidBind .size() ==0 ){
                qaCodeBuff = qaCode + "_" + 1;
            }else{
                String str = lstRfidBind.get(lstRfidBind.size()-1).getQaCode();
                qaCodeBuff = qaCode+"_" + Integer.parseInt(str.substring(str.lastIndexOf("_"),str.length()-1))+1;
            }

            storageInfo.setQaCode(qaCodeBuff);
            storageInfo.setMeter(leftMeter);
            storageInfo.setInStorageTime(new Date());
            storageInfo.setInStorageId(outStorageDetail.getOutStorageId());
            //待重新绑定rfid
            storageInfo.setState(3);
            storageInfoDAO.updateById(storageInfo);

	        RfidBind rfidBind = new RfidBind();
            rfidBind.setMaterialCode(outStorageDetail.getMaterialCode());
            rfidBind.setBatchNo(batchNoAndrfid);
            rfidBind.setQaCode(qaCodeBuff);
            rfidBind.setRfid(batchNoAndrfid);
            rfidBind.setMeter(leftMeter);
            rfidBind.setType("0");
            rfidBind.setSalesCode(outStorageDetail.getSalesname()==null?"":outStorageDetail.getSalesname());
            rfidBind.setWarehouseCode(outStorageDetail.getWarehouseCode()==null?"":outStorageDetail.getWarehouseCode());
            rfidBind.setDishnumber(outStorageDetail.getDishnumber());
	        //组织编号
            rfidBind.setOrg(outStorageDetail.getOrg()==null?"":outStorageDetail.getOrg());
	        Map<String,Object> mapinfo = rfidBindDAO.getMaterialInfo(rfid);
	        //产线id
            rfidBind.setFactoryid(mapinfo.get("FACTORYID")==null?"":mapinfo.get("FACTORYID").toString());
	        //段号
            rfidBind.setSegmentno(mapinfo.get("SEGMENTNO")==null?"":mapinfo.get("SEGMENTNO").toString());
	        //颜色
            rfidBind.setColour(mapinfo.get("COLOUR")==null?"":mapinfo.get("COLOUR").toString());
	        //重量
            rfidBind.setWeight(mapinfo.get("WEIGHT")==null?"":mapinfo.get("WEIGHT").toString());
	        //销售订单行号
            rfidBind.setOrderline(outStorageDetail.getOrderline()==null?"":outStorageDetail.getOrderline());
	        //销售订单号
            rfidBind.setOrdernum(outStorageDetail.getOrderno()==null?"":outStorageDetail.getOrderno());
            //盘编号
            rfidBind.setDishnumber(mapinfo.get("DISHNUMBER")==null?"":mapinfo.get("DISHNUMBER").toString());
            //盘号(返回给EBS)
            rfidBind.setDishcode(mapinfo.get("DISHCODE")==null?"":mapinfo.get("DISHCODE").toString());
            //单位
            rfidBind.setUnit(mapinfo.get("UNIT")==null?"":mapinfo.get("UNIT").toString());
            //销售订单头
            rfidBind.setOeheader(mapinfo.get("OEHEADER")==null?"":mapinfo.get("OEHEADER").toString());
            //销售订单行
            rfidBind.setOeline(mapinfo.get("OELINE")==null?"":mapinfo.get("OELINE").toString());
            //位置
            rfidBind.setLocationid(mapinfo.get("LOCATIONID")==null?"":mapinfo.get("LOCATIONID").toString());
            //客户id
            rfidBind.setCustomerid(mapinfo.get("CUSTOMERID")==null?"":mapinfo.get("CUSTOMERID").toString());
	        rfidBindDAO.insert(rfidBind);
	        
	        //调按米出库接口
	        Car car = carDAO.selectOne(new Car() {{
	        	setCode(outStorageDetail.getCarCode());
	        }});
	        if(car!=null) {
	        	car.setState(2L);
	        	carDAO.updateById(car);
	        }
	        return new PdaResult();
        }
    }

    /**
     * 模块：调拨出库管理
     * 接口编号：3.1
     * 功能描述: 获取详情列表
     * 入参：userId
     * 返回：详情表列表 状态为已开始,未完成的
     */
    @Override
    public PdaResult alloStorageOutList(Long userId,String carCode) {
        User user = userDAO.selectById(userId);
        if (user == null || user.getFactoryCode() == null){
            return new PdaResult(1, "用户异常", "");
        }
        return new PdaResult(allocationDetailDAO.selectList(new EntityWrapper<AllocationDetail>()
                .eq("OUTCARCODE",carCode)
                .eq("STATE",2)
                .in("ORG", user.getFactoryCode())));
    }

    /**
     * 模块：调拨出库管理
     * 接口编号：3.2
     * 功能描述: 出库完成
     * 入参：rfid,userId(用户id)
     * 返回：PdaResult
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PdaResult alloStorageOutSuccess(String rfid, Long userId) {
        List<AllocationDetail> lstAllocationDetail = allocationDetailDAO.selectByMap(new HashMap<String, Object>() {{
            put("RFID", rfid);
            put("STATE", 2);
        }});
        if (lstAllocationDetail == null || lstAllocationDetail.size()<=0){
            return new PdaResult(1, "不存在该RFID或已经完成开始出库!", "");
        }
        AllocationDetail allocationDetail = lstAllocationDetail.get(0);
        List<StorageInfo> lstStorageInfo = storageInfoDAO.selectByMap(new HashMap<String, Object>() {{
            put("RFID", rfid);
        }});
        if (lstStorageInfo == null){
            return new PdaResult(1, "数据异常!", "");
        }
        Allocation allocation = allocationDAO.selectById(allocationDetail.getPId());

        AlloOutStorage alloOutStorage = new AlloOutStorage();
        alloOutStorage.setOrg(allocationDetail.getOrg());
        alloOutStorage.setBatchNo(allocationDetail.getBatchNo());
        alloOutStorage.setMaterialCode(allocationDetail.getMaterialCode());
        alloOutStorage.setQaCode(allocationDetail.getQaCode());
        alloOutStorage.setSalesCode(allocationDetail.getSalesCode());
        alloOutStorage.setSalesName(allocationDetail.getSalesName());
        alloOutStorage.setRfid(allocationDetail.getRfid());
        alloOutStorage.setMeter(allocationDetail.getMeter());
        alloOutStorage.setCarCode(allocationDetail.getOutCarCode());
        alloOutStorage.setShelfCode(allocationDetail.getOutShelfCode());
        alloOutStorage.setWarehouseCode(allocation.getOutWarehouseCode());
        alloOutStorage.setStartStorageTime(allocationDetail.getStartOutStorageTime());
        alloOutStorage.setOutstoragetime(new Date());
        alloOutStorage.setOutStorageId(userId);
        alloOutStorage.setState(4);
        alloOutStorage.setDishnumber(allocationDetail.getDishnumber());
        alloOutStorageDAO.insert(alloOutStorage);

        storageInfoDAO.deleteById(lstStorageInfo.get(0).getId());

        allocationDetail.setState(3);
        allocationDetail.setOutStorageTime(new Date());
        allocationDetail.setOutStorageId(userId);
        allocationDetailDAO.updateById(allocationDetail);

        Car car = carDAO.selectOne(new Car() {{
        	setCode(allocationDetail.getOutCarCode());
        }});
        if(car!=null) {
        	car.setState(2L);
        	carDAO.updateById(car);
        }
        //库位可用
        Shelf shelf = shelfDAO.selectOne(new Shelf() {{
        	setCode(allocationDetail.getOutShelfCode());
        }});
        if(shelf!=null) {
        	shelf.setState(1);
        	shelfDAO.updateById(shelf);
        }
        return new PdaResult();
    }

    /**
     * 模块：调拨入库管理
     * 接口编号：3.3
     * 功能描述: 获取详情列表
     * 入参：userId,carCode
     * 返回：详情表列表 状态为已开始,未完成的
     */
    @Override
    public PdaResult alloStorageInList(Long userId,String carCode) {
        User user = userDAO.selectById(userId);
        if (user == null || user.getFactoryCode() == null){
            return new PdaResult(1, "用户异常", "");
        }
        return new PdaResult(allocationDetailDAO.selectByMap(new HashMap<String, Object>(3) {{
            put("ORG", user.getFactoryCode());
            put("INCARCODE",carCode);
            put("STATE",4);
        }}));
    }

    /**
     * 模块：调拨入库管理
     * 接口编号：3.4
     * 功能描述: 入库完成
     * 入参：rfid,shelfCode(库位编码),userId(用户id)
     * 返回：PdaResult
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PdaResult alloStorageInSuccess(String rfid, Long userId,String shelfCode) {
        List<AllocationDetail> lstAllocationDetail = allocationDetailDAO.selectByMap(new HashMap<String, Object>() {{
            put("RFID", rfid);
            put("STATE", 4);
        }});
        if (lstAllocationDetail == null || lstAllocationDetail.size() != 1) {
            return new PdaResult(1, "数据异常", "");
        }
        AllocationDetail allocationDetail = lstAllocationDetail.get(0);
        if (allocationDetail.getState() != 4) {
            return new PdaResult(1, "请先开始调拨入库!", "");
        }
        
        //调EBS调拨接口
    	Map<String,Object> xmlMap = new HashMap<>(1);
		xmlMap.put("line",new HashMap<String,Object>(4){{
			put("org",allocationDetail.getOrg());
			put("batchno",allocationDetail.getBatchNo());
            //新仓库
			put("inwarehouse",allocationDetail.getWarehouseCode());
            //新库位
			put("inLocation",allocationDetail.getShelfCode());
		}});
		
		interfaceDoService.insertDo("FEWMS008", "EBS接口-调拨、移库接口", JSONObject.toJSONString(xmlMap), DateUtils.getTime(),allocationDetail.getQaCode(),
                allocationDetail.getBatchNo(),null, "");

        allocationDetail.setState(5);
        allocationDetail.setInStorageTime(new Date());
        allocationDetail.setInStorageId(userId);
        allocationDetail.setShelfCode(shelfCode);
        allocationDetailDAO.updateById(allocationDetail);

        AlloInStorage alloInStorage = new AlloInStorage();
        alloInStorage.setOrg(allocationDetail.getOrg());
        alloInStorage.setMaterialCode(allocationDetail.getMaterialCode());
        alloInStorage.setBatchNo(allocationDetail.getBatchNo());
        alloInStorage.setQaCode(allocationDetail.getQaCode());
        alloInStorage.setSalesCode(allocationDetail.getSalesCode());
        alloInStorage.setSalesName(allocationDetail.getSalesName());
        alloInStorage.setRfid(allocationDetail.getRfid());
        alloInStorage.setMeter(allocationDetail.getMeter());
        alloInStorage.setShelfCode(shelfCode);
        alloInStorage.setCarCode(allocationDetail.getInCarCode());
        alloInStorage.setWarehouseCode(allocationDetail.getInWarehouseCode());
        alloInStorage.setStartStorageTime(allocationDetail.getStartInStorageTime());
        alloInStorage.setInstorageTime(new Date());
        alloInStorage.setEntityNo(allocationDetail.getEntityNo());
        alloInStorage.setDishnumber(allocationDetail.getDishnumber());
        alloInStorageDAO.insert(alloInStorage);

        StorageInfo storageInfo = new StorageInfo();
        storageInfo.setMaterialCode(allocationDetail.getMaterialCode());
        storageInfo.setBatchNo(allocationDetail.getBatchNo());
        storageInfo.setQaCode(allocationDetail.getQaCode());
        storageInfo.setShelfCode(shelfCode);
        storageInfo.setWarehouseCode(allocationDetail.getInWarehouseCode());
        storageInfo.setMeter(allocationDetail.getMeter());
        storageInfo.setRfid(allocationDetail.getRfid());
        storageInfo.setInStorageTime(new Date());
        storageInfo.setOrg(allocationDetail.getOrg());
        storageInfo.setSalesCode(allocationDetail.getSalesCode());
        storageInfo.setSalesName(allocationDetail.getSalesName());
        storageInfo.setInStorageId(allocationDetail.getInStorageId());
        storageInfo.setEntityNo(allocationDetail.getEntityNo());
        storageInfo.setDishnumber(allocationDetail.getDishnumber());

        //根据rfid获取到订单号、订单行号
        Map<String,Object> mapinfo=rfidBindDAO.getMaterialInfo(rfid);
        //设置订单号
        storageInfo.setOrderline(mapinfo.get("ORDERLINE")==null?"":mapinfo.get("ORDERLINE").toString());
        //设置订单行号
        storageInfo.setOrderno(mapinfo.get("ORDERNUM")==null?"":mapinfo.get("ORDERNUM").toString());

        storageInfoDAO.insert(storageInfo);
        
        //恢复行车状态为可用
        Car car = carDAO.selectOne(new Car() {{
        	setCode(allocationDetail.getInCarCode());
        }});
        if(car!=null) {
        	car.setState(2L);
        	carDAO.updateById(car);
        }
        
        //库位不可用
        Shelf shelf = shelfDAO.selectOne(new Shelf() {{
        	setCode(allocationDetail.getInShelfCode());
        	setWarehouseCode(allocationDetail.getWarehouseCode());
        	setFactoryCode(allocationDetail.getOrg());
        }});
        if(shelf!=null) {
        	shelf.setState(0);
        	shelfDAO.updateById(shelf);
        }
        return new PdaResult();
    }

    /**
     * 模块：移库出库管理
     * 接口编号：4.1
     * 功能描述: 获取详情列表
     * 入参：userId,carCode
     * 返回：详情表列表 状态为已开始,未完成的
     */
    @Override
    public PdaResult moveStorageOutList(Long userId,String carCode) {
        User user = userDAO.selectById(userId);
        if (user == null || user.getFactoryCode() == null) {
            return new PdaResult(1, "用户异常", "");
        }
        return new PdaResult(moveStorageDetailDAO.selectList(new EntityWrapper<MoveStorageDetail>()
                .eq("OUTCARCODE",carCode)
                .eq("STATE", 2)
                .in("ORG", user.getFactoryCode())));
    }

    /**
     * 模块：移库出库管理
     * 接口编号：4.1
     * 功能描述: 移库出库完成
     * 入参：userId
     * 返回：详情表列表 状态为已开始,未完成的
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PdaResult moveStorageOutSuccess(String rfid, Long userId) {
        List<MoveStorageDetail> lstMoveStorageDetail = moveStorageDetailDAO.selectByMap(new HashMap<String, Object>() {{
            put("RFID", rfid);
            put("STATE", 2);
        }});
        if (lstMoveStorageDetail == null || lstMoveStorageDetail.size() != 1){
            return new PdaResult(1, "数据异常", "");
        }
        MoveStorageDetail moveStorageDetail = lstMoveStorageDetail.get(0);
        if (moveStorageDetail.getState() != 2){
            return new PdaResult(1, "请提交开始出库的数据!", "");
        }
        List<StorageInfo> lstStorageInfo = storageInfoDAO.selectByMap(new HashMap<String, Object>() {{
            put("RFID", rfid);
        }});
        if (lstStorageInfo == null || lstStorageInfo.size() == 0){
            return new PdaResult(1, "库存表中无此RFID数据!", "");
        }
        moveStorageDetail.setState(3);
        moveStorageDetail.setOutstoragetime(new Date());
        moveStorageDetail.setOutStorageId(userId);
        moveStorageDetailDAO.updateById(moveStorageDetail);

        MoveOutStorage moveOutStorage = new MoveOutStorage();
        moveOutStorage.setOrg(moveStorageDetail.getOrg());
        moveOutStorage.setMaterialCode(moveStorageDetail.getMaterialCode());
        moveOutStorage.setBatchNo(moveStorageDetail.getBatchNo());
        moveOutStorage.setQaCode(moveStorageDetail.getQaCode());
        moveOutStorage.setDishnumber(moveStorageDetail.getDishnumber());
        moveOutStorage.setSalesCode(moveStorageDetail.getSalesCode());
        moveOutStorage.setSalesName(moveStorageDetail.getSalesName());
        moveOutStorage.setRfid(moveStorageDetail.getRfid());
        moveOutStorage.setMeter(moveStorageDetail.getMeter());
        moveOutStorage.setShelfCode(moveStorageDetail.getOutShelfCode());
        moveOutStorage.setWarehouseCode(moveStorageDetail.getWarehouseCode());
        moveOutStorage.setCarCode(moveStorageDetail.getOutCarCode());
        moveOutStorage.setStartStorageTime(moveStorageDetail.getStartOutStorageTime());
        moveOutStorage.setOutStorageTime(moveStorageDetail.getOutstoragetime());
        moveOutStorage.setOutStorageId(moveStorageDetail.getOutStorageId());
        moveOutStorageDAO.insert(moveOutStorage);
        storageInfoDAO.deleteById(lstStorageInfo.get(0).getId());
        Car car = carDAO.selectOne(new Car() {{
        	setCode(moveStorageDetail.getCarCode());
        }});
        if(car!=null) {
        	car.setState(2L);
        	carDAO.updateById(car);
        }
        return new PdaResult();
    }

    /**
     * 模块：移库入库管理
     * 接口编号：4.3
     * 功能描述: 获取详情列表
     * 入参：userId，carCode
     * 返回：详情表列表 状态为已开始,未完成的
     */
    @Override
    public PdaResult moveStorageInList(Long userId,String carCode) {
        User user = userDAO.selectById(userId);
        if (user == null || user.getFactoryCode() == null){
            return new PdaResult(1, "用户异常", "");
        }
        return new PdaResult(moveStorageDetailDAO.selectList(new EntityWrapper<MoveStorageDetail>()
                .eq("INCARCODE",carCode)
                .eq("STATE", 4)
                .in("ORG", user.getFactoryCode())));
    }

    /**
     * 模块：移库入库管理
     * 接口编号：4.4
     * 功能描述: 入库完成
     * 入参：rfid,shelfCode(库位编码),userId(用户id)
     * 返回：PdaResult
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PdaResult moveStorageInSuccess(String rfid, Long userId,String shelfId) {
        List<MoveStorageDetail> lstMoveStorageDetail = moveStorageDetailDAO.selectByMap(new HashMap<String, Object>() {{
            put("RFID", rfid);
            put("STATE", 4);
        }});
        if (lstMoveStorageDetail == null || lstMoveStorageDetail.size() != 1) {
            return new PdaResult(1, "数据异常", "");
        }
        MoveStorageDetail moveStorageDetail = lstMoveStorageDetail.get(0);
        if (moveStorageDetail.getState() != 4) {
            return new PdaResult(1, "请先开始调拨入库!", "");
        }
        
        List<InstorageDetail> instroragedetails = instorageDetailDAO.selectByMap(new HashMap<String, Object>() {{
            put("RFID", rfid);
        }});
    	if (instroragedetails == null || instroragedetails.size() == 0){
            return new PdaResult(1, "暂无此数据", "");
        }
    	InstorageDetail instorageDetail = instroragedetails.get(0);
        
        //调EBS移库接口
    	Map<String,Object> xmlMap = new HashMap<>(1);
		xmlMap.put("line",new HashMap<String,Object>(4){{
			put("org",instorageDetail.getOrg());
			put("batchno",moveStorageDetail.getBatchNo());
            //新仓库
			put("inwarehouse",moveStorageDetail.getWarehouseCode());
            //新库位
			put("inLocation",moveStorageDetail.getShelfCode());
		}});
		
		interfaceDoService.insertDo("FEWMS008", "EBS接口-调拨、移库接口", JSONObject.toJSONString(xmlMap), DateUtils.getTime(),moveStorageDetail.getQaCode(),
                moveStorageDetail.getBatchNo(), null, "");

        moveStorageDetail.setState(5);
        moveStorageDetail.setInStorageTime(new Date());
        moveStorageDetail.setInStorageId(userId);
        moveStorageDetail.setShelfCode(parseLong(shelfId));
        moveStorageDetailDAO.updateById(moveStorageDetail);

        MoveInStorage moveInStorage = new MoveInStorage();
        moveInStorage.setOrg(moveStorageDetail.getOrg());
        moveInStorage.setMaterialCode(moveStorageDetail.getMaterialCode());
        moveInStorage.setBatchNo(moveStorageDetail.getBatchNo());
        moveInStorage.setQaCode(moveStorageDetail.getQaCode());
        moveInStorage.setDishnumber(moveStorageDetail.getDishnumber());
        moveInStorage.setSalesCode(moveStorageDetail.getSalesCode());
        moveInStorage.setSalesName(moveStorageDetail.getSalesName());
        moveInStorage.setRfid(moveStorageDetail.getRfid());
        moveInStorage.setMeter(moveStorageDetail.getMeter());
        moveInStorage.setShelfCode(shelfId);
        moveInStorage.setCarCode(moveStorageDetail.getInCarCode());
        moveInStorage.setWarehouseCode(moveStorageDetail.getWarehouseCode());
        moveInStorage.setInStorageId(userId);
        moveInStorage.setInstorageTime(new Date());
        moveInStorage.setEntityNo(moveStorageDetail.getEntityNo());
        moveInStorageDAO.insert(moveInStorage);

        StorageInfo storageInfo = new StorageInfo();
        storageInfo.setMaterialCode(moveStorageDetail.getMaterialCode());
        storageInfo.setBatchNo(moveStorageDetail.getBatchNo());
        storageInfo.setQaCode(moveStorageDetail.getQaCode());
        storageInfo.setShelfCode(shelfId);
        storageInfo.setWarehouseCode(moveStorageDetail.getWarehouseCode());
        storageInfo.setMeter(moveStorageDetail.getMeter());
        storageInfo.setRfid(moveStorageDetail.getRfid());
        storageInfo.setInStorageTime(new Date());
        storageInfo.setOrg(moveStorageDetail.getOrg());
        storageInfo.setSalesCode(moveStorageDetail.getSalesCode());
        storageInfo.setSalesName(moveStorageDetail.getSalesName());
        storageInfo.setInStorageId(moveStorageDetail.getInStorageId());
        storageInfo.setEntityNo(moveStorageDetail.getEntityNo());
        //根据rfid获取到订单号、订单行号
        Map<String,Object> mapinfo=rfidBindDAO.getMaterialInfo(rfid);
        //设置订单号
        storageInfo.setOrderline(mapinfo.get("ORDERLINE")==null?"":mapinfo.get("ORDERLINE").toString());
        //设置订单行号
        storageInfo.setOrderno(mapinfo.get("ORDERNUM")==null?"":mapinfo.get("ORDERNUM").toString());
        storageInfo.setDishnumber(moveStorageDetail.getDishnumber());
        storageInfoDAO.insert(storageInfo);
       
        //恢复行车状态为可用
        Car car  = carDAO.selectOne(new Car() {{
            setCode(moveStorageDetail.getInCarCode());
        }});
        if(car!=null) {
        	car.setState(2L);
        	carDAO.updateById(car);
        }
        
        //库位不可用
        Shelf shelf = shelfDAO.selectOne(new Shelf() {{
        	setCode(moveStorageDetail.getInShelfCode());
        	setWarehouseCode(moveStorageDetail.getWarehouseCode());
        	setFactoryCode(moveStorageDetail.getOrg());
        }});
        if(shelf!=null) {
        	shelf.setState(0);
        	shelfDAO.updateById(shelf);
        }
        return new PdaResult();
    }

    /**
     * 模块：拆分管理
     * 接口编号：55TFSI
     * 功能描述: 获取状态为“已开始”的拆分入库物料
     * 入参：carCode(行车编码)
     * 返回：PdaResult
     */
    @Override
    public PdaResult getSplitInstorageList(String carCode) {
        return new PdaResult(splitInstorageDAO.selectByMap(new HashMap<String,Object>(2){{
            put("STATE",1);
            put("carCode",carCode);
        }}));
    }
    
    /**
     * 模块：拆分
     * 拆分完成入库
     * @param rfid;
     * @param shelfId :库位号
     * @param userId
     * @return PdaResult
     */
    @Override
    public PdaResult endInstorage(String rfid, String shelfId,String userId) {
        SplitInstorage splitInstorage = splitInstorageDAO.getInstorageSplit(rfid,"");
        StorageInfo storageInfo = new StorageInfo();
        storageInfo.setMaterialCode(splitInstorage.getMaterialCode());
        storageInfo.setBatchNo(splitInstorage.getBatchNo());
        storageInfo.setQaCode(splitInstorage.getQaCode());
        storageInfo.setShelfCode(shelfId);
        storageInfo.setMeter(splitInstorage.getMeter());
        storageInfo.setRfid(rfid);
        storageInfo.setSalesName(splitInstorage.getSalesName());
        storageInfo.setSalesCode(splitInstorage.getSalesCode());
        storageInfo.setInStorageTime(new Date());
        storageInfo.setInStorageId(parseLong(userId));
        storageInfo.setOrg(userDAO.selectById(userId).getFactoryCode());

        //根据rfid获取到订单号、订单行号
        Map<String,Object> mapinfo=rfidBindDAO.getMaterialInfo(rfid);
        //设置订单号
        storageInfo.setOrderline(mapinfo.get("ORDERLINE")==null?"":mapinfo.get("ORDERLINE").toString());
        //设置订单行号
        storageInfo.setOrderno(mapinfo.get("ORDERNUM")==null?"":mapinfo.get("ORDERNUM").toString());

        storageInfoDAO.insert(storageInfo);

        return new PdaResult();
    }

    /**
     * 根据用户获取厂区
     * @param  userId
     * @return List<FactoryArea>
     */
    @Override
    public PdaResult getFactorys(String userId){
        return new PdaResult(factoryAreaDAO.selectList(new EntityWrapper<FactoryArea>().in("CODE", userDAO.selectById(valueOf(userId)).getFactoryCode())));
    }

}
